#!/usr/bin/ruby

MAX=50
INTERVAL=0.025

$n=0

a=ARGV.collect { |x| Integer(x) }
a=Array.new(MAX,MAX).collect { |x| Integer( rand() * x ) } if a.length() == 0

def print_array( a )
  system "clear"
  MAX.downto(1) {
    |line|
    for v in a do
      print v>=line ? '|' : ' '
    end
    print "\n"
  }
end

def compare( a, b )
  return a > b
end

def swap( array, a, b )
  t = array[a]
  array[a] = array[b]
  array[b] = t
  print_array( array )
  puts $n
  $n=$n+1
  sleep INTERVAL
end

def combsort( array )
  print_array(array)
  gap = array.size()
  swapped = true
  while gap>1 and swapped
    swapped = false
    gap = Integer( gap > 1.25 ? gap / 1.25 : 1 )
    for i in 0..array.size()-gap-1 do
      if compare( array[i], array[i+gap] )
	swap(array,i,i+gap)
	swapped = true
      end
    end
  end
  return array
end

a=combsort(a)
print_array(a)
